<?php
declare (strict_types = 1);

namespace app\controller\api;

use app\BaseController;
use app\model\User;
use app\service\WechatService;
use think\facade\Config;

class Auth extends BaseController
{
    protected $wechatService;
    
    public function __construct()
    {
        parent::__construct();
        $this->wechatService = new WechatService();
    }
    
    /**
     * 获取微信授权URL
     */
    public function getAuthUrl()
    {
        $redirectUri = Config::get('wechat.redirect_uri');
        $url = $this->wechatService->getAuthUrl($redirectUri);
        return json(['code' => 0, 'data' => ['url' => $url]]);
    }
    
    /**
     * 微信授权回调
     */
    public function callback()
    {
        $code = input('code');
        if (!$code) {
            return json(['code' => 1, 'msg' => '参数错误']);
        }
        
        $result = $this->wechatService->getUserInfo($code);
        if (!$result) {
            return json(['code' => 1, 'msg' => '获取用户信息失败']);
        }
        
        // 查找或创建用户
        $user = User::where('openid', $result['openid'])->find();
        if (!$user) {
            $user = new User;
            $user->openid = $result['openid'];
            $user->save();
        }
        
        // 生成token
        $token = md5($user->id . time() . rand(1000, 9999));
        $user->token = $token;
        $user->save();
        
        return json([
            'code' => 0,
            'data' => [
                'token' => $token,
                'user' => $user
            ]
        ]);
    }
    
    /**
     * 更新用户信息
     */
    public function updateUserInfo()
    {
        $token = input('token');
        $user = User::where('token', $token)->find();
        if (!$user) {
            return json(['code' => 401, 'msg' => '请先登录']);
        }
        
        $data = input('post.');
        $user->nickname = $data['nickname'] ?? '';
        $user->avatar = $data['avatar'] ?? '';
        $user->phone = $data['phone'] ?? '';
        $user->save();
        
        return json(['code' => 0, 'msg' => '更新成功']);
    }
} 